<?php

class test_loader
{

	/**
	 * @var test_results
	 */
	protected $test_results;

	protected $stat_file_count = 0;

	protected $stat_class_count = 0;

	protected $stat_method_count = 0;

	public function __construct()
	{
		global $test_results;
		$this->test_results = $test_results;
	}

	public function run()
	{
		$this->remove_old_results_data();
		$error_files_suffix = substr(md5(rand()), 0, 10) . ".html";
		global $error;
		/* @var $error error */
		$classes = get_declared_classes();
		dir_map(PATH_OPENID . "/_tests", array($this, "_include_files"));
		$classes = array_diff(get_declared_classes(), $classes);
		foreach ($classes as $class)
		{
			if (substr($class, -5, 5) != "_test")
			{
				continue;
			}
			$class_instance = new $class();
			$this->stat_class_count++;
			$class_instance->set_up();
			$methods = get_class_methods($class);
			foreach ($methods as $method)
			{
				if (substr($method, -5, 5) == "_test")
				{
					$class_instance->$method();
					if ($error->is_error_occured())
					{
						$error_file_name = "{$class}-{$method}-{$error_files_suffix}";
						file_put_contents(PATH_HOME . "/last_errors/{$error_file_name}", $error->get_errors_html());
						$this->test_results->add_error("Error occured while running {$class}::{$method}()", $error_file_name);
					}
					$error->clear_errors();
					$this->stat_method_count++;
				}
			}
			$class_instance->tear_down();
		}
	}

	public function _include_files($file_name)
	{
		if (substr($file_name, -9, 9) == ".test.php" and !strpos($file_name, "/base."))
		{
			require_once($file_name);
			$this->stat_file_count++;
		}
	}

	public function remove_old_results_data()
	{
		$dir = PATH_HOME . "/last_errors";
		foreach (scandir($dir) as $file_name)
		{
			$file_path = $dir . "/" . $file_name;
			if ($file_name[0] != "." and !is_dir($file_path))
			{
				unlink($file_path);
			}
		}
	}

	public function get_stat_file_count()
	{
		return $this->stat_file_count;
	}

	public function get_stat_class_count()
	{
		return $this->stat_class_count;
	}

	public function get_stat_method_count()
	{
		return $this->stat_method_count;
	}

}

?>